package com.seemovies.sdk.mvp.impl;

import com.seemovies.sdk.mvp.base.BasePresenter;
import com.seemovies.sdk.mvp.base.BaseView;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by Jarchie on 2017\11\7.
 * 描述：基础处理类的实现类
 */

@SuppressWarnings("WeakerAccess")
public abstract class BasePresenterImpl<V extends BaseView> implements BasePresenter {
    protected V view;
    //将所有正在处理的Subscription都添加到CompositeSubscription中，统一退出的时候注销观察
    private CompositeDisposable mCompositeDisposable;

    public BasePresenterImpl(V view) {
        this.view = view;
        start();
    }

    @Override
    public void start() {
    }

    @Override
    public void detach() {
        this.view = null;
        unDisposable();
    }

    /*****************************以下为配合RxJava2+Retrofit2使用的*****************************/

    /**
     * 添加Disposable
     *
     * @param subscription
     */
    @Override
    public void addDisposable(Disposable subscription) {
        //如果解绑了的话添加sb需要新的实例，否则绑定是无效的
        if (mCompositeDisposable == null || mCompositeDisposable.isDisposed()) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);
    }

    //在界面退出等需要解绑观察者的情况下调用此方法统一解绑，防止Rx造成的内存泄漏
    @Override
    public void unDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

}
